package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.vo.PageVO;
import com.etoak.entity.Dishes;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.DishesVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.validation.constraints.NotBlank;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  服务实现类
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {

    @Override
    public void add(Dishes dishes) {
        Dishes saveDishes = getByName(dishes.getName());
        if (ObjectUtils.isNotEmpty(saveDishes)) {
            throw new CustomException("菜品已存在");
        }
        dishes.setCreateTime(DateUtil.now());
        this.save(dishes);
    }

    @Override
    public List<DishesVO> getList(Dishes dishes) {
        return baseMapper.getList(dishes);
    }

    @Override
    public PageVO<DishesVO> listPage(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum, pageSize);
        List<DishesVO> dishesVOS = this.getList(dishes);
        PageInfo<DishesVO> pageInfo = new PageInfo<>(dishesVOS);
        return new PageVO<>(dishesVOS, pageInfo.getTotal());
    }

    @Override
    public void updateDishes(int id, Dishes dishes) {
        if (!ObjectUtils.isNotEmpty(getById(id))) {
            throw new CustomException("菜品不存在");
        }
        String dishesName = dishes.getName();
        if (StringUtils.isNotEmpty(dishesName)) {
            Dishes byName = getByName(dishesName);
            if (ObjectUtils.isNotEmpty(byName) && !byName.getId().equals(id)) {
                throw new CustomException("菜品名字重复");
            }
        }
        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        this.updateById(dishes);
    }

    @Override
    public void deleteDishes(int id) {
        if (!ObjectUtils.isNotEmpty(getById(id))) {
            throw new CustomException("菜品不存在");
        }
        this.removeById(id);
    }

    @Override
    public List<DishesVO> getByIds(List<Integer> ids) {
        return baseMapper.getByIds(ids);
    }

    private Dishes getByName(@NotBlank(message = "菜品名称不能为空") String name) {
        return lambdaQuery().eq(Dishes::getName, name).one();
    }
}
